import router from "@/router/index";
import { getToken } from "./loginInfo";
import { Notification } from 'element-ui';
import nProgress from "nprogress";
import "nprogress/nprogress.css";

//  全局前置守卫
router.beforeEach((to, from, next) => {
  nProgress.start();
  const token = getToken(); // 是否有token
  const isLogin = !!token;  // 是否已登录
  const isLoginPage = to.path === "/"; // 是否访问登录页
  const requiresAuth = to.meta.isAuth; // 当前路由是否需要登录

  if(isLoginPage) {
    if(isLogin){
      Notification({
        type: "error",
        message: "您已登录，不可以访问登录页面",
        title: "提示"
      });
      next({ path: "/home" });
    }else{
      next();
    }
    return;
  }

  if(requiresAuth){
    if(isLogin){
      next();
    } else {
      Notification({
        type: "error",
        message: "请先登录",
        title: "提示"
      });
      next({ path: "/" });
    }
    return; 
  }
  next();
});


//  全局后置守卫
router.afterEach((to) => {
  document.title = `Eleming${to.meta.title}`;
  nProgress.done();
});